package com.wang.controller;


import com.wang.base.http.RestResponse;
import com.wang.base.util.TokenUtil;
import com.wang.base.util.WeekDateUtil;
import com.wang.domain.TongueDiagnosis;
import com.wang.domain.TonguePicItem;
import com.wang.domain.User;
import com.wang.domain.enums.DiagnosisCoatedEnum;
import com.wang.domain.enums.DiagnosisColorEnum;
import com.wang.domain.enums.DiagnosisCrackEnum;
import com.wang.domain.enums.DiagnosisIndentationEnum;
import com.wang.model.Diagnosis.SelectDiagnosisVM;
import com.wang.model.EchartsVM;
import com.wang.service.TongueDiagnosisService;
import com.wang.service.TonguePicItemService;
import com.wang.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author WangZai
 * @since 2023-04-27
 */
@CrossOrigin
@RestController
@RequestMapping("/td/api/tongueDiagnosis")
@Api(tags = "舌诊结果模块接口说明")
public class TongueDiagnosisController {
    private final ModelMapper modelMapper;
    private final UserService userService;
    private final TongueDiagnosisService tongueDiagnosisService;
    private final TonguePicItemService tonguePicItemService;

    private static final Logger log = LoggerFactory.getLogger(TongueDiagnosisController.class);

    @Autowired
    public TongueDiagnosisController(ModelMapper modelMapper, UserService userService, TongueDiagnosisService tongueDiagnosisService, TonguePicItemService tonguePicItemService) {
        this.modelMapper = modelMapper;
        this.userService = userService;
        this.tongueDiagnosisService = tongueDiagnosisService;
        this.tonguePicItemService = tonguePicItemService;
    }


    /**
     * 功能描述 保存诊断结果接口
     *
     * @param authentication
     * @param file
     * @param coated
     * @param color
     * @param crack
     * @param indentation
     * @param diagnosis
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveDiagnosis")
    @ApiOperation("保存诊断结果接口")
    public RestResponse<Object> saveDiagnosis(@RequestHeader("authentication") String authentication, @RequestParam("file") MultipartFile file,
                                              @RequestParam("coated") String coated, @RequestParam("color") String color,
                                              @RequestParam("crack") String crack, @RequestParam("indentation") String indentation,
                                              @RequestParam("diagnosis") String diagnosis) {
        String userName = TokenUtil.getUserInfoFromToken(authentication);
        User user = userService.getUserByUserName(userName);
        String uuid = UUID.randomUUID().toString();
        try {
            byte[] bytes = file.getBytes();
            TonguePicItem tonguePicItem = new TonguePicItem();
            tonguePicItem.setUUID(uuid);
            tonguePicItem.setPicData(bytes);
            log.info("图片保存结果：" + tonguePicItemService.saveTonguePicItem(tonguePicItem));
        } catch (IOException e) {
            e.printStackTrace();
        }
        TonguePicItem tonguePicItem = tonguePicItemService.getTonguePicItemByUUID(uuid);
        TongueDiagnosis tongueDiagnosis = new TongueDiagnosis();
        tongueDiagnosis.setTonguePicItemId(tonguePicItem.getTonguePicItemId());
        tongueDiagnosis.setUserId(user.getUserId());
        for (DiagnosisCoatedEnum diagnosisCoatedEnum : DiagnosisCoatedEnum.values()) {
            if (diagnosisCoatedEnum.getName().equals(coated)) {
                tongueDiagnosis.setCoated(diagnosisCoatedEnum);
            }
        }
        for (DiagnosisColorEnum diagnosisColorEnum : DiagnosisColorEnum.values()) {
            if (diagnosisColorEnum.getName().equals(color)) {
                tongueDiagnosis.setColor(diagnosisColorEnum);
            }
        }

        for (DiagnosisCrackEnum diagnosisCrackEnum : DiagnosisCrackEnum.values()) {
            if (diagnosisCrackEnum.getName().equals(crack)) {
                tongueDiagnosis.setCrack(diagnosisCrackEnum);
            }
        }
        for (DiagnosisIndentationEnum diagnosisIndentationEnum : DiagnosisIndentationEnum.values()) {
            if (diagnosisIndentationEnum.getName().equals(indentation)) {
                tongueDiagnosis.setIndentation(diagnosisIndentationEnum);
            }
        }

        tongueDiagnosis.setDiagnosis(diagnosis);
        if (tongueDiagnosisService.saveTongueDiagnosis(tongueDiagnosis)) {
            return RestResponse.ok("保存成功！");
        } else {
            return RestResponse.failure("保存失败！！！");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @GetMapping(value = "/deleteDiagnosis/{tongueDiagnosisId}")
    @ApiOperation("删除诊断结果接口")
    public RestResponse<Object> deleteDiagnosis(@PathVariable Integer tongueDiagnosisId) {
        TongueDiagnosis tongueDiagnosis = tongueDiagnosisService.getTongueDiagnosisById(tongueDiagnosisId);
        if(tongueDiagnosisService.deleteTongueDiagnosisById(tongueDiagnosisId)&&tonguePicItemService.deleteTonguePicItem(tongueDiagnosis.getTonguePicItemId())){
            return RestResponse.ok("删除成功");
        }else {
            return RestResponse.failure("删除失败！！！");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/selectDiagnosis")
    @ApiOperation("查询诊断结果接口")
    public RestResponse<Object> selectDiagnosis(@RequestHeader("authentication") String authentication) {
        String userName = TokenUtil.getUserInfoFromToken(authentication);
        User user = userService.getUserByUserName(userName);
        List<TongueDiagnosis> list = tongueDiagnosisService.getTongueDiagnosisListByUserId(user.getUserId());
        List<SelectDiagnosisVM> selectDiagnosisVMList = new ArrayList<>();
        for (TongueDiagnosis tongueDiagnosis : list) {
            SelectDiagnosisVM selectDiagnosisVM = modelMapper.map(tongueDiagnosis, SelectDiagnosisVM.class);
            if (tongueDiagnosis.getCoated() != null) {
                selectDiagnosisVM.setCoated(tongueDiagnosis.getCoated().getName());
            }
            if (tongueDiagnosis.getColor() != null) {
                selectDiagnosisVM.setColor(tongueDiagnosis.getColor().getName());
            }
            if (tongueDiagnosis.getCrack() != null) {
                selectDiagnosisVM.setCrack(tongueDiagnosis.getCrack().getName());
            }
            if (tongueDiagnosis.getIndentation() != null) {
                selectDiagnosisVM.setIndentation(tongueDiagnosis.getIndentation().getName());
            }
            selectDiagnosisVMList.add(selectDiagnosisVM);
        }
        if (selectDiagnosisVMList.isEmpty()) {
            return RestResponse.failure("无相关诊断结果！");
        } else {
            return RestResponse.ok(selectDiagnosisVMList);
        }
    }



    @GetMapping(value = "/selectRecordDate")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("查询诊断记录日期分布")
    public RestResponse<Object> selectRecordDate(){
        List<TongueDiagnosis> tongueDiagnosisList = tongueDiagnosisService.getAllDiagnosis();
        List<Integer[]> list = new ArrayList<>();
        Integer[] diagnosisArray = {0, 0, 0, 0, 0, 0, 0};
        List<String> lastWeekDayList = WeekDateUtil.getLastWeekDayList();
        if(tongueDiagnosisList.isEmpty()){
            return RestResponse.failure("无相关记录");
        }else {
            for(TongueDiagnosis tongueDiagnosis:tongueDiagnosisList){
                Date date = tongueDiagnosis.getCreateTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            sdf1.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                String dateStr = sdf.format(date);
                for (int i = 0; i < lastWeekDayList.size(); i++) {
                    if (lastWeekDayList.get(i).equals(dateStr)) {
                        diagnosisArray[i] += 1;
                    }
                }
            }
            list.add(diagnosisArray);
            return RestResponse.ok(list);
        }
    }

    @GetMapping(value = "/selectDiagnosis/coatedNum")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("获取舌苔分布接口说明")
    public RestResponse<Object> selectDiagnosisCoatedNum() {
        List<TongueDiagnosis> tongueDiagnosisList = tongueDiagnosisService.getAllDiagnosis();
        if (tongueDiagnosisList.isEmpty()) {
            return RestResponse.failure("没有符合条件的记录");
        } else {
            List<EchartsVM> list = new ArrayList<>();

            int nocoatedNum = tongueDiagnosisService.getCoatedNum(DiagnosisCoatedEnum.NOCOATED.getCode());
            EchartsVM nocoatedModel = new EchartsVM();
            nocoatedModel.setName(DiagnosisCoatedEnum.NOCOATED.getName());
            nocoatedModel.setValue(nocoatedNum);
            list.add(nocoatedModel);

            int whiteNum = tongueDiagnosisService.getCoatedNum(DiagnosisCoatedEnum.WHITE.getCode());
            EchartsVM whitedModel = new EchartsVM();
            whitedModel.setName(DiagnosisCoatedEnum.WHITE.getName());
            whitedModel.setValue(whiteNum);
            list.add(whitedModel);

            int yellowNum = tongueDiagnosisService.getCoatedNum(DiagnosisCoatedEnum.YELLOW.getCode());
            EchartsVM yellowModel = new EchartsVM();
            yellowModel.setName(DiagnosisCoatedEnum.YELLOW.getName());
            yellowModel.setValue(yellowNum);
            list.add(yellowModel);

            return RestResponse.ok(list);
        }
    }

    @GetMapping(value = "/selectDiagnosis/colorNum")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("获取舌质分布接口说明")
    public RestResponse<Object> selectDiagnosisColorNum() {
        List<TongueDiagnosis> tongueDiagnosisList = tongueDiagnosisService.getAllDiagnosis();
        if (tongueDiagnosisList.isEmpty()) {
            return RestResponse.failure("没有符合条件的记录");
        } else {
            List<EchartsVM> list = new ArrayList<>();

            int crimsonNum = tongueDiagnosisService.getColorNum(DiagnosisColorEnum.CRIMSON.getCode());
            EchartsVM crimsonModel = new EchartsVM();
            crimsonModel.setName(DiagnosisColorEnum.CRIMSON.getName());
            crimsonModel.setValue(crimsonNum);
            list.add(crimsonModel);



            int redNum = tongueDiagnosisService.getColorNum(DiagnosisColorEnum.RED.getCode());
            EchartsVM redModel = new EchartsVM();
            redModel.setName(DiagnosisColorEnum.RED.getName());
            redModel.setValue(redNum);
            list.add(redModel);

            int whiteNum = tongueDiagnosisService.getColorNum(DiagnosisColorEnum.WHITE.getCode());
            EchartsVM whitedModel = new EchartsVM();
            whitedModel.setName(DiagnosisColorEnum.WHITE.getName());
            whitedModel.setValue(whiteNum);
            list.add(whitedModel);
            return RestResponse.ok(list);
        }
    }


    @GetMapping(value = "/selectDiagnosis/crackNumAndIndentNum")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("获取裂纹和齿痕分布接口说明")
    public RestResponse<Object> selectDiagnosisCrackNumAndIndentNum() {
        List<TongueDiagnosis> tongueDiagnosisList = tongueDiagnosisService.getAllDiagnosis();
        if (tongueDiagnosisList.isEmpty()) {
            return RestResponse.failure("没有符合条件的记录");
        } else {
            List<EchartsVM> list = new ArrayList<>();

            int crackNum = tongueDiagnosisService.getCrackNum(DiagnosisCrackEnum.CRACK.getCode());
            EchartsVM crackModel = new EchartsVM();
            crackModel.setName(DiagnosisCrackEnum.CRACK.getName());
            crackModel.setValue(crackNum);
            list.add(crackModel);

            int crackNormalNum = tongueDiagnosisService.getCrackNum(DiagnosisCrackEnum.NORMAL.getCode());
            EchartsVM crackNormalModel = new EchartsVM();
            crackNormalModel.setName(DiagnosisCrackEnum.NORMAL.getName());
            crackNormalModel.setValue(crackNormalNum);
            list.add(crackNormalModel);

            int indentNum = tongueDiagnosisService.getIndentNum(DiagnosisIndentationEnum.INDENTATION.getCode());
            EchartsVM indentModel = new EchartsVM();
            indentModel.setName(DiagnosisIndentationEnum.INDENTATION.getName());
            indentModel.setValue(indentNum);
            list.add(indentModel);

            int indentNormalNum = tongueDiagnosisService.getIndentNum(DiagnosisIndentationEnum.NORMAL.getCode());
            EchartsVM indentNormalModel = new EchartsVM();
            indentNormalModel.setName(DiagnosisIndentationEnum.NORMAL.getName());
            indentNormalModel.setValue(indentNormalNum);
            list.add(indentNormalModel);
            return RestResponse.ok(list);
        }
    }
}

